package tech.aistar.clothesspringboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import tech.aistar.clothesspringboot.mapper.UserMapper;
import tech.aistar.clothesspringboot.pojo.result.ResultReturn;
import tech.aistar.clothesspringboot.service.UserService;

import org.springframework.stereotype.Service;
import tech.aistar.clothesspringboot.utils.JwtUtils;
import tech.aistar.pojo.User;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResultReturn loginByName(User user) {
        //根据用户名查询用户信息
        User u = userMapper.selectByUsername(user.getUsername());
        if(u == null){
            return ResultReturn.fail("用户名不存在");
        }
        //判断密码是否正确
        //对密码进行MD5加密
        String md5Password =DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if(!md5Password.equals(u.getPassword())){
            return ResultReturn.fail("密码错误");
        }
        //TODO 生成jwt令牌
        String token = JwtUtils.generateToken(u);
        //TODO ysx 返回token和username
        Map<String, Object> map = BeanUtil.beanToMap(u);
        map.put("token", token);
        return ResultReturn.success(map);
    }

    @Override
    public int insertUser(User user) {
        //对密码进行MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Password);
        //设置默认值
        user.setRole(1);
        user.setStatus(1);
        return userMapper.insertUser(user);
    }

}
